<?php
declare (strict_types=1);

namespace app\command;

use app\model\Change;
use app\model\User;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\db\Where;
use think\Exception;
use think\facade\Db;
use think\Model;
use utils\AES;

class Test extends Command
{

    //AES加密
    protected function configure()
    {
        var_dump($this->Bole());
        die;
//        var_dump(sha1('123456'));die;
//        $arr = AES::decrypt('DaZZZwB1bGZIc7wW6fnSKVQuoMzRUi/osJARMg5okk2zF6G82Zg7RkjJu/fuyUrv5Zhbq58U3tYW2VkKXz5+y0iuD77M9uO2k5HUrsx6MzM+WxegKfGI0wNZ7dIVicyX');
//        var_dump(AES::encrypt($arr));die;
        $user = User::where('id', 200)->find();
        $this->acting($user->id, $user->p_id, $user->path);
        die;

    }


    /**
     * ①蜜蜂奖
     * @param $user_id
     * @param $path
     * @return bool
     */
    public function acting($user_id, $parent_id, $path)
    {
        Db::startTrans();
        try {
            if ($path != '') {
                $amount = 699;
                //寻找我的上级
                $users = array_reverse(explode(',', $path));
                $slice = array_slice($users, 0, 3);
                $num = 0;
                foreach ($slice as $v) {
                    $user = User::where('id', $v)->find();
                    if ($user && $user->vip != 0) {
                        switch ($num) {
                            case 0: //直推
                                $rate = 30;
                                break;
                            case 1: //间推一代奖
                                $rate = 10;
                                break;
                            case 2: //间推二代奖
                                $rate = 8;
                                break;
                        }
                        //设置用户余额以及增加资金记录
                        $money = $amount * $rate / 100;
                        //---后期可修改为批量添加与批量修改用户余额 ???xxx事务造成的幻读
                        if ($money > 0) {
                            Change::SetUserMoney($user->id, $user->money, $money, 4);
                            $user->money += $money;
                            $user->save();
                        }

                    }
                    $num++;
                }
            }
            //②发放培育奖励
            $this->TeamLeader($parent_id);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }


    /**
     * ②桃李奖
     * 查看自己是否能升级为团队长
     * @param $parent_id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function TeamLeader($parent_id)
    {
        $parent = User::where('id', $parent_id)->find();
        if ($parent_id != 0 && $parent && $parent->is_leader == 0) {
            //一.查看直属上级的下面购买699的人数是否>=3 是：直属上级成为团队长 并且给直属上级的上级发放100元奖励
            //二.首先要知道上级目前是不是团队长 是：不是执行第一步
            $lowerLevelNum =
                Db::name('user')
                    ->alias('a')
                    ->leftJoin('change b', 'a.id = b.user_id')
                    ->where(['a.p_id' => $parent_id, 'b.type' => 3])
                    ->group('a.id')
                    ->count(); //购买vip的人数数量
            if ($lowerLevelNum >= 3) {
                $parent->is_leader = 1;
                $parent->save();
                //给上级的上级发放100元奖励
                $parentFather = User::where('id', $parent->p_id)->find();
                if ($parentFather) {
                    Change::SetUserMoney($parent->p_id, $parentFather->money, 100, 5);
                    $parentFather->money += 100;
                    $parentFather->start_id = 1;
                    $parentFather->save();
                }
            }
        }
    }


    /**
     * ③伯乐奖
     * @return bool
     */
    public function Bole()
    {
        Db::startTrans();
        try {
            $amount = 5960;
            //本月开始结束时间
            $date = date("Y-m-d");
            $monthStart = date('Y-m-01 00:00:00', strtotime($date));
            $monthEnd = date('Y-m-d 23:59:59', strtotime("$monthStart +1 month -1 day"));
            $change = Db::name('change')
                ->alias('a')
                ->leftJoin('user b', 'a.user_id = b.id')
                ->field('a.user_id,b.p_id')
                ->where(['a.type' => 3])
                ->whereBetween('a.created_time', [$monthStart, $monthEnd])
                ->group('a.user_id')
                ->select()
                ->toArray();
            if (!empty($change)) {
                $item = array();
                foreach ($change as $k => $v) {
                    if (array_key_exists($v['p_id'], $item)) {
                        $item[$v['p_id']]['number'] += 1;
                    } else {
                        $item[$v['p_id']]['p_id'] = $v['p_id'];
                        $item[$v['p_id']]['number'] = 1;
                    }
                }
            }
            //大于500的条件时触发
            $number = count($item);
            if ($number >= 2) {
                //数组排序
                $item = arraySort($item, 'number', SORT_DESC);
                //计算每个人能发多少钱
                $price = round($amount / $number, 3);
                $users = Db::name('user')
                    ->field('id as user_id,money,money as before_money')
                    ->where('id', 'in', array_column($item, 'p_id'));
                $users_data = $users->select()->toArray();
                foreach ($users_data as &$v) {
                    $v['money'] = $price;
                    $v['after_money'] = $v['before_money'] + $price;
                    $v['type'] = 5;
                }
                //更改用户余额
                $model = new Change();
                $model->saveAll($users_data);
                $users->inc('money', $price)->update();
                Db::commit();
            }
        } catch (\Exception $exception) {
            Db::rollback();
            return false;
        }
    }


    //④被动收益
    public function passiveIncome($user_id, $parent_id, $path)
    {
        Db::startTrans();
        try {
            if ($path != '') {
                $amount = 699;
                //寻找我的上级
                $users = array_reverse(explode(',', $path));
                $slice = array_slice($users, 0, 3);
                $num = 0;
                foreach ($slice as $v) {
                    $num++;
                    $user = User::where('id', $v)->find();
                    if ($user && $user->start_id >=3) {
                        switch ($num) {
                            case $user->start_id>=10 && $num = 1://直推
                                $rate = 30;
                                break;
                            case $user->start_id>=5 && $num = 2://1级
                                $rate = 10;
                                break;
                            case $user->start_id>=3 && $num = 3://2级
                                $rate = 8;
                                break;
                        }
                        //设置用户余额以及增加资金记录
                        $money = $amount * $rate / 100;
                        //---后期可修改为批量添加与批量修改用户余额 ???xxx事务造成的幻读
                        if ($money > 0) {
                            Change::SetUserMoney($user->id, $user->money, $money, 4);
                            $user->money += $money;
                            $user->save();
                        }

                    }
                }
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }
}
